<?php

namespace App\Kuafu\Order\Controller\Merchant;

use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Base\Enum\BaseCodeEnum;
use App\Kuafu\Order\Enum\OrderCacheEnum;
use App\Kuafu\Order\Enum\OrderMerchantEnum;
use App\Kuafu\Order\Service\OrderMerchantUseService;
use App\Kuafu\Order\Service\OrderService;
use App\Kuafu\Order\Enum\OrderCodeEnum;
use App\Kuafu\Order\Exceptions\OrderException;
use App\Kuafu\Order\Service\OrderPayService;
use App\Kuafu\Order\Validate\OrderMerchantValidate;
use App\Kuafu\WaiMai\Service\WaiMaiOrderService;
use Illuminate\Http\JsonResponse;
use App\Kuafu\Order\Service\OrderStatisticsService;
use App\Kuafu\Order\Enum\CodeEnum;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class OrderController extends BaseController
{
    /**
     * 合并的 - 订单概览
     * @param Request $request
     */
    public function combineOrderOverview(Request $request)
    {
        $showTimeTab = (int)$request->get('showTimeTab', OrderMerchantEnum::SHOW_TIME_TAB_TODAY);
        $showStartAt = (int)$request->get('showStartAt', 0);
        $showEndAt   = (int)$request->get('showEndAt', 0);
        $orderType   = (int)$request->get('orderType', OrderMerchantEnum::ORDER_TYPE_IN);
        $sourceType  = (int)$request->get('sourceType', 0);

        $validate = OrderMerchantValidate::combineOrderOverview($request);
        if ($validate) {
            return $this->fail(OrderCodeEnum::ERR_ORDER_PARAM_VALID, $validate);
        }

        $data = (new OrderMerchantUseService([$this->shopId]))
            ->setShowTimeTab($showTimeTab, $showStartAt, $showEndAt)
            ->orderOverview($orderType, $sourceType);

        return $this->success($data);
    }

    // 合并的 - 折线图
    public function combineOrderChart(Request $request)
    {
        $showTimeTab    = (int)$request->get('showTimeTab', OrderMerchantEnum::SHOW_TIME_TAB_TODAY);
        $showStartAt    = (int)$request->get('showStartAt', 0);
        $showEndAt      = (int)$request->get('showEndAt', 0);
        $statisticsType = (int)$request->get('statisticsType', OrderMerchantEnum::STAT_ORIGINAL_PRICE);
        $orderType      = (int)$request->get('orderType', OrderMerchantEnum::ORDER_TYPE_IN);
        $sourceType     = (int)$request->get('sourceType', 0);

        $validate = OrderMerchantValidate::combineOrderChart($request);
        if ($validate) {
            return $this->fail(OrderCodeEnum::ERR_ORDER_PARAM_VALID, $validate);
        }

        if ($orderType == OrderMerchantEnum::ORDER_TYPE_TOTAL) {
            return $this->fail(OrderCodeEnum::ERR_ORDER_IN_OUT_TYPE_ONE);
        }

        $data = (new OrderMerchantUseService([$this->shopId]))
            ->setShowTimeTab($showTimeTab, $showStartAt, $showEndAt)
            ->orderCharts($statisticsType, $orderType, $sourceType);

        return $this->success($data);
    }

    // 合并的 - 订单列表
    public function combineOrderList(Request $request)
    {
        $showTimeTab = (int)$request->get('showTimeTab', OrderMerchantEnum::SHOW_TIME_TAB_TODAY);
        $showStartAt = (int)$request->get('showStartAt', 0);
        $showEndAt   = (int)$request->get('showEndAt', 0);
        $pageSize    = $request->get('pageSize', 20);
        $pageNum     = $request->get('pageNum', 1);
        $orderType   = (int)$request->get('orderType', OrderMerchantEnum::ORDER_TYPE_IN);
        $sourceType  = (int)$request->get('sourceType', 0);
        $distributionId  = (int)$request->get('distributionId', 0);//渠道ID

        $validate = OrderMerchantValidate::combineOrderList($request);
        if ($validate) {
            return $this->fail(OrderCodeEnum::ERR_ORDER_PARAM_VALID, $validate);
        }

        $data = (new OrderMerchantUseService([$this->shopId]))
            ->setShowTimeTab($showTimeTab, $showStartAt, $showEndAt)
            ->orderListsUse($orderType, $pageSize, $pageNum, $sourceType, $distributionId);

        return $this->success($data);
    }

    // 店内订单详情
    public function inOrderDetail(Request $request, $orderId)
    {
        $orderId = (int)$orderId;
        $detail  = OrderService::bOrderDetail($orderId, $this->brandId, 0, $this->shopId);
        if (null === $detail) {
            return $this->fail(BaseCodeEnum::NOT_FOUND, '订单不存在');
        }
        return $this->success($detail);
    }

    // 店内订单 - 套餐详情
    public function packageProductDetail(Request $request)
    {
        $orderId  = (int)$request->get('orderId');
        $detailId = (int)$request->get('detailId');

        $detail = OrderService::packageProductDetail($orderId, $this->shopId, $detailId);
        if (!$detail) {
            return $this->fail(BaseCodeEnum::NOT_FOUND, '订单不存在');
        }
        return $this->success($detail);
    }

    // 外卖订单详情
    public function waiMaiOrderDetail(Request $request, $orderId)
    {
        $orderId = (int)$orderId;
        return $this->success(WaiMaiOrderService::orderDetail($orderId));
    }

    /**
     * 时段营业额统计
     * @param Request $request
     */
    public function timeIntervalBusinessStatistics(Request $request)
    {
        $startAt          = (int)$request->startAt;
        $endAt            = (int)$request->endAt;
        $step             = (int)$request->step * 60;
        $service          = new OrderStatisticsService();
        $sourceType       = explode(',', $request->sourceType);
        $shopId           = $this->shopId;
        $divisionTime     = $service->divisionTime($startAt, $endAt, $step);
        $divisionTimeDate = $service->timeIntervalBusinessStatistics($shopId, $sourceType, $divisionTime);
        return $this->success($divisionTimeDate);
    }


    public function productSellStatistics(Request $request)
    {
        $type     = (int)$request->type ?: 1;
        $shopId   = $this->shopId;
        $startAt  = (int)$request->startAt;
        $endAt    = (int)$request->endAt;
        $orderBy  = $request->orderBy ?: 'num';
        $byType   = $request->byType ?: 'desc';
        $typeName = CodeEnum::SELLING_STATISTICS_CODE_TEXT[$type];
        //查询该时间段店铺所有订单信息
        $service        = new OrderStatisticsService();
        $sellStatistics = $service->productSellStatistics($typeName, $shopId, $startAt, $endAt, $orderBy, $byType);
        return $this->success($sellStatistics);
    }

    /**
     * 获取上个月实际收入
     * @throws OrderException
     */
    public function getMonthActualIncome(Request $request): JsonResponse
    {
        try {
            return $this->success(OrderPayService::getMonthIncome($request->header('shopId')));
        } catch (\Exception $exception) {
            throw new OrderException(OrderCodeEnum::ERR_ORDER_COUNT_MONTH_PRICE, '', $exception);
        }
    }


    /**
     * 店铺结算（日结单）
     * @param Request $request
     * @return JsonResponse
     * @throws OrderException
     */
    public function calcShopTrade(Request $request): JsonResponse
    {
        $startTime = $request->get('startDate', strtotime(date('Ymd')));
        $endTime   = $request->get('endDate', strtotime(date('Ymd')));
        $shopId    = (int)$request->header('shopId');

        if ($endTime - $startTime > 60 * 60 * 24 * 31) {
            throw new OrderException(OrderCodeEnum::ERR_QUERY_TIME);
        }

        try {
            $data = OrderService::sCalcShopTrade($shopId, $startTime, $endTime);
        } catch (\Exception $e) {
            throw new OrderException(OrderCodeEnum::ERR_ORDER_STATIC, '', $e);
        }

        return $this->success($data);
    }

}
